package com.fastmms.analysis;

import com.fastmms.utils.ByteUtil;

import java.io.IOException;
import java.io.RandomAccessFile;

public class AnalysisByte {
    private RandomAccessFile msgFile;
    private AnalysisBlock block;

    private long fileLength;
    private long startPoint;
    private long endPoint;
    private byte[] BYTE_DATA_ARRAY;
    private int DATA_POINT;
    private int DATA_LIMIT;

    private AnalysisByte(){}

    public AnalysisByte(RandomAccessFile msgFile,int size){
        this.msgFile = msgFile;
        try {
            this.fileLength = msgFile.length();
            BYTE_DATA_ARRAY = new byte[size];
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public AnalysisByte initData(AnalysisBlock block) throws Exception{
        if( this.fileLength < block.getEndPoint() ){
            throw new Exception( "文件移动地址超出消息块界限！file Length :"+this.fileLength+" , block endPoint:"+ block.getEndPoint() );
        }
        clearAnalysisData();
        this.block = block;
        startPoint = block.getStartPoint();
        endPoint = block.getEndPoint();
        int blockSize = (int) (endPoint - startPoint);
        /*if(BYTE_DATA_ARRAY == null || BYTE_DATA_ARRAY.length < size){
            BYTE_DATA_ARRAY = new byte[size];
        }*/
        msgFile.seek(startPoint);
        msgFile.read(BYTE_DATA_ARRAY,0, blockSize );
        DATA_LIMIT = blockSize;
        return this;
    }
    public void clearAnalysisData(){
        block = null;
        startPoint = 0;
        endPoint = 0;
        DATA_POINT = 0;
    }

    public void close(){
        clearAnalysisData();
        try {
            msgFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean hasNext(){
        return DATA_POINT < DATA_LIMIT;
    }

    public int readInt(){
        int value = ByteUtil.toInt(BYTE_DATA_ARRAY,DATA_POINT);
        DATA_POINT += 4;
        return value;
    }

    public void movePoint(int size){
        DATA_POINT += size;
    }

    public int read(byte readData[]){
        int readSize = -1;
        try {
            System.arraycopy(BYTE_DATA_ARRAY, DATA_POINT, readData,0, readData.length);
            DATA_POINT += readData.length;
        }catch (Exception e){
            e.printStackTrace();
        }
        return readSize;
    }

    public RandomAccessFile getMsgFile() {
        return msgFile;
    }

    public void setMsgFile(RandomAccessFile msgFile) {
        this.msgFile = msgFile;
    }

    public AnalysisBlock getBlock() {
        return block;
    }

    public void setBlock(AnalysisBlock block) {
        this.block = block;
    }
}
